const express = require("express");
const router = express.Router();
const { success, failure } = require("../utils/response");
const { Course, Category, User } = require("../models");
const { setKey, getKey } = require("../utils/redis");
const logger = require('../utils/logger')

// 查询首页数据
router.get("/home", async (req, res) => {
  try {
    // 焦点图
    const condition = {
      attributes: {
        exclude: ["CategoryId", "categoryId", "userId", "userid", "content"],
      },
      include: [
        {
          model: Category,
          attributes: ["id", "name"],
          as: "category",
        },
        {
          model: User,
          attributes: ["id", "username", "nickname", "avatar", "company"],
          as: "user",
        },
      ],
      where: {
        recommended: true,
      },
      order: [["id", "DESC"]],
      limit: 10,
    };
    const recommendedCourse = await Course.findAll(condition);
    // 人气课程
    const likesCourse = await Course.findAll({
      attributes: {
        exclude: ["CategoryId", "categoryId", "userId", "userid", "content"],
      },
      order: [["likesCount", "DESC"]],
      limit: 10,
    });
    // 入门课程
    const introCourse = await Course.findAll({
      attributes: {
        exclude: ["CategoryId", "categoryId", "userId", "userid", "content"],
      },
      where: {
        introductory: true,
      },
      order: [["id", "DESC"]],
      limit: 10,
    });
    success(res, "获取首页数据成功。", {
      recommendedCourse,
      likesCourse,
      introCourse,
    });
  } catch (error) {
    logger.error(error)
    failure(res, error);
  }
});

// 查询首页数据(promise,redis)

router.get("/promise/home", async (req, res) => {
  try {
    // 从缓存中获取数据
    const cacheKey = "index";
    let indexData = await getKey(cacheKey);
    if (indexData) {
      return success(res, "查询热点数据成功！", { indexData });
    }
    // 从数据库中获取数据
    const [recommendedCourse,likesCourse,introCourse] = await Promise.all([
      // 焦点图
      Course.findAll({
        attributes: { exclude: ["CategoryId", "UserId", "content"] },
        include: [
          {
            model: Category,
            as: "category",
            attributes: ["id", "name"],
          },
          {
            model: User,
            as: "user",
            attributes: ["id", "username", "nickname", "avatar", "company"],
          },
        ],
        where: {
          recommended: true,
        },
        order: [["id", "DESC"]],
        limit: 10,
      }),
      // 人气课程
      Course.findAll({
        attributes: {
          exclude: ["CategoryId", "categoryId", "userId", "userid", "content"],
        },
        order: [["likesCount", "DESC"]],
        limit: 10,
      }),
      // 入门课程
      Course.findAll({
        attributes: {
          exclude: ["CategoryId", "categoryId", "userId", "userid", "content"],
        },
        where: {
          introductory: true,
        },
        order: [["id", "DESC"]],
        limit: 10,
      })
    ]);
    
    indexData = {
      recommendedCourse,
      likesCourse,
      introCourse
    }
    // 设置缓存过期时间，为30分钟
    await setKey(cacheKey,indexData,30*60)
    success(res,"查询热点数据成功",indexData)
  } catch (error) {
    failure(res, error);
  }
});

module.exports = router;
